package com.qulai.web.controller.amazon_us;

import com.qulai.amazon_us.domain.amazon_us.AmazonUsRecord;
import com.qulai.amazon_us.domain.amazon_us.bo.AmazonUsRecordExportBo;
import com.qulai.amazon_us.domain.amazon_us.dto.AmazonUsRecordDto;
import com.qulai.amazon_us.service.amazon_us.IAmazonUsRecordService;
import com.qulai.common.annotation.Log;
import com.qulai.common.core.controller.BaseController;
import com.qulai.common.core.domain.AjaxResult;
import com.qulai.common.core.domain.entity.SysDictData;
import com.qulai.common.core.page.PageDomain;
import com.qulai.common.core.page.TableDataInfo;
import com.qulai.common.enums.BusinessType;
import com.qulai.common.utils.DictUtils;
import com.qulai.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 记录明细Controller
 *
 * @author hunan
 * @date 2025-01-05
 */
@RestController
@RequestMapping("/amazon_us/record")
public class AmazonUsRecordController extends BaseController {
    @Autowired
    private IAmazonUsRecordService amazonUsRecordService;

    /**
     * 查询记录明细列表: 分表前的接口
     */
//    @PreAuthorize("@ss.hasPermi('amazon_us:record:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(AmazonUsRecord amazonUsRecord) {
//        startPage();
//        List<AmazonUsRecord> list = amazonUsRecordService.selectAmazonUsRecordList(amazonUsRecord);
//        return getDataTable(list);
//    }

    /**
     * 查询记录明细列表: 分表后的接口
     */

    @PreAuthorize("@ss.hasPermi('amazon_us:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(AmazonUsRecordDto amazonUsRecord, PageDomain pageDomain) {

        if (amazonUsRecord.getShop() == null || amazonUsRecord.getShop().isEmpty() ){
           return getDataTable_v2((List<?>) new ArrayList<>(), 0L);
        }


        // 手动分页控制
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        // 查询总数
        Long total = amazonUsRecordService.countAmazonUsRecordList_v2(amazonUsRecord);

        // 查询分页数据
        List<AmazonUsRecord> list = Collections.emptyList();
        if (total > 0) {
            // 设置分页参数
            amazonUsRecord.setOffset((pageNum - 1) * pageSize);
            amazonUsRecord.setLimit(pageSize);
            list = amazonUsRecordService.selectAmazonUsRecordList_v2(amazonUsRecord);
        }

        // 返回分页结果
        return getDataTable_v2(list, total);
    }

//    /**
//     * 导出记录明细列表
//     */
//    @PreAuthorize("@ss.hasPermi('amazon_us:record:export')")
//    @Log(title = "记录明细", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, AmazonUsRecord amazonUsRecord) {
//        List<AmazonUsRecord> list = amazonUsRecordService.selectAmazonUsRecordList(amazonUsRecord);
//        ExcelUtil<AmazonUsRecord> util = new ExcelUtil<AmazonUsRecord>(AmazonUsRecord.class);
//        util.exportExcel(response, list, "记录明细数据");
//    }

    /**
     * 导出记录明细列表：分表之后导出
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:record:export')")
    @Log(title = "记录明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AmazonUsRecordDto amazonUsRecord) {

        List<AmazonUsRecord> list = amazonUsRecordService.selectAmazonUsRecordList_v2(amazonUsRecord);

        ExcelUtil<AmazonUsRecord> util = new ExcelUtil<AmazonUsRecord>(AmazonUsRecord.class);
        util.exportExcel(response, list, "记录明细数据");
    }

    @PreAuthorize("@ss.hasPermi('amazon_us:record:export')")
    @Log(title = "记录明细", businessType = BusinessType.EXPORT)
	@PostMapping("/exportAllShop")
	public void exportAllShop(HttpServletResponse response, AmazonUsRecordDto amazonUsRecord) {
		class EntryBytes { String name; byte[] data; EntryBytes(String n, byte[] d){ this.name = n; this.data = d; } }
		List<EntryBytes> entries = new ArrayList<>();

		List<String> shops = amazonUsRecord.getShop();
		if (shops == null || shops.isEmpty()) {
			List<SysDictData> dictDataList = DictUtils.getDictCache("amazon_us_shop_list");
			if (dictDataList != null) {
				shops = dictDataList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
			}
		}
		if (shops == null || shops.isEmpty()) {
			return;
		}

		for (String shop : shops) {
			List<String> shopList = new ArrayList<>();
			shopList.add(shop);
			amazonUsRecord.setShop(shopList);
			List<AmazonUsRecordExportBo> list = amazonUsRecordService.exportAmazonUsRecordList(amazonUsRecord);
			ExcelUtil<AmazonUsRecordExportBo> util = new ExcelUtil<AmazonUsRecordExportBo>(AmazonUsRecordExportBo.class);
			byte[] bytes = util.exportExcelToBytes(list, shop.toLowerCase(), "");
			if (bytes != null && bytes.length > 0) {
				entries.add(new EntryBytes(shop.toLowerCase() + ".xlsx", bytes));
			}
		}

		String zipName = "records_" + System.currentTimeMillis() + ".zip";
		java.util.zip.ZipOutputStream zos = null;
		try {
			response.setContentType("application/zip");
			response.setCharacterEncoding("utf-8");
			String encoded = java.net.URLEncoder.encode(zipName, "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
			zos = new java.util.zip.ZipOutputStream(response.getOutputStream());
			for (EntryBytes eb : entries) {
				java.util.zip.ZipEntry entry = new java.util.zip.ZipEntry(eb.name);
				zos.putNextEntry(entry);
				zos.write(eb.data);
				zos.closeEntry();
			}
			zos.finish();
		} catch (Exception e) {
			// 忽略异常以避免打断下载
		} finally {
			if (zos != null) { try { zos.close(); } catch (Exception ignore) {} }
		}
	}


    /**
     * 获取记录明细详细信息
     */
//    @PreAuthorize("@ss.hasPermi('amazon_us:record:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//
//        return success(amazonUsRecordService.selectAmazonUsRecordById(id));
//    }

    /**
     * 获取记录明细详细信息： 分表之后
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:record:query')")
    @GetMapping("/shopRecord")
    public AjaxResult shopRecord(AmazonUsRecord amazonUsRecord) {

        if (amazonUsRecord.getShop() == null || amazonUsRecord.getShop().isEmpty() ){
            return error("店铺不能为空");
        }

        return success(amazonUsRecordService.selectAmazonUsRecordByShopAndId(amazonUsRecord));
    }


    /**
     * 新增记录明细
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:record:add')")
    @Log(title = "记录明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AmazonUsRecord amazonUsRecord) {
        return toAjax(0);
    }

//    /**
//     * 修改记录明细
//     */
//    @PreAuthorize("@ss.hasPermi('amazon_us:record:edit')")
//    @Log(title = "记录明细", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody AmazonUsRecord amazonUsRecord) {
//        amazonUsRecord.setUpdateBy(getUsername());
//        return toAjax(amazonUsRecordService.updateAmazonUsRecord(amazonUsRecord));
//    }

    /**
     * 修改记录明细: 分表后的
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:record:edit')")
    @Log(title = "记录明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AmazonUsRecord amazonUsRecord) {

        if (amazonUsRecord.getShop() == null || amazonUsRecord.getShop().isEmpty() ){
            return error("店铺不能为空");
        }

        amazonUsRecord.setUpdateBy(getUsername());
        return toAjax(amazonUsRecordService.updateAmazonUsRecord_v2(amazonUsRecord));
    }

    /**
     * 删除记录明细
     */
    /*

            @PreAuthorize("@ss.hasPermi('amazon_us:record:remove')")
            @Log(title = "记录明细", businessType = BusinessType.DELETE)
            @DeleteMapping("/{ids}")
            public AjaxResult remove(@PathVariable Long[] ids) {
                return toAjax(amazonUsRecordService.deleteAmazonUsRecordByIds(ids));
            }
     */


}
